package flc.ast.activity;

import androidx.appcompat.app.AppCompatActivity;

import android.app.Dialog;
import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;

import com.bigkoo.pickerview.adapter.ArrayWheelAdapter;
import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.blankj.utilcode.util.KeyboardUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.Glide;
import com.contrarywind.adapter.WheelAdapter;
import com.contrarywind.listener.OnItemSelectedListener;
import com.contrarywind.view.WheelView;
import com.stark.picselect.PhotoSelectorBuilder;
import com.stark.picselect.config.PhotoConfig;
import com.stark.picselect.entity.SelectMediaEntity;
import com.stark.picselect.interfaces.OnSelectResultListener;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import flc.ast.BaseAc;
import flc.ast.R;
import flc.ast.bean.CityJsonBean;
import flc.ast.bean.WeddingBean;
import flc.ast.databinding.ActivityMakeCardBinding;
import flc.ast.utils.CityLevelsListDate;
import stark.common.basic.event.EventStatProxy;
import stark.common.basic.utils.StkPermissionHelper;

public class MakeCardActivity extends BaseAc<ActivityMakeCardBinding> {

    public static int position;
    private OptionsPickerView pvOptions;
    private CityLevelsListDate levelsListDate;
    private ArrayList<CityJsonBean> jsonBeans;
    private ArrayList<ArrayList<String>> arrayLists;
    private ArrayList<ArrayList<ArrayList<String>>> arrayLists1;
    private Dialog mySelDateDialog, mySelTimeDialog;
    private WheelView wheelView1, wheelView2, wheelView3, wheelView4, wheelView5;
    private SimpleDateFormat format = new SimpleDateFormat("yyyy.MM.dd");
    private String selDate, selPath = "";


    @Override
    protected int onCreate() {
        return R.layout.activity_make_card;
    }

    @Override
    protected void initView() {
        EventStatProxy.getInstance().statEvent1(this, mDataBinding.event1Container);
        EventStatProxy.getInstance().statEvent5(this, mDataBinding.event5Container);

        mDataBinding.ivMakeCardBack.setOnClickListener(v -> onBackPressed());

        mDataBinding.ivMakeCardComplete.setOnClickListener(this);
        mDataBinding.tvWeddingDate.setOnClickListener(this);
        mDataBinding.tvWeddingHost.setOnClickListener(this);
        mDataBinding.tvUploadCover.setOnClickListener(this);
        mDataBinding.ivCoverDelete.setOnClickListener(this);

        //选择日期弹框
        selDateDialog();
        //选择时间弹框
        selTimeDialog();
    }

    @Override
    protected void onClickCallback(View v) {
        switch (v.getId()) {
            case R.id.ivMakeCardComplete://完成
                String groomName = mDataBinding.etGroom.getText().toString();
                if (TextUtils.isEmpty(groomName)) {
                    ToastUtils.showShort(R.string.et_groom_name_tips);
                    return;
                }
                String brideName = mDataBinding.etBride.getText().toString();
                if (TextUtils.isEmpty(brideName)) {
                    ToastUtils.showShort(R.string.et_bride_name_tips);
                    return;
                }
                String weddingDate = mDataBinding.tvWeddingDate.getText().toString();
                if (TextUtils.isEmpty(weddingDate)) {
                    ToastUtils.showShort(R.string.sel_wedding_date_tips);
                    return;
                }
                String locationName = mDataBinding.tvWeddingHost.getText().toString();
                if (TextUtils.isEmpty(locationName)) {
                    ToastUtils.showShort(R.string.sel_wedding_host_tips);
                    return;
                }
                String addressName = mDataBinding.etAddress.getText().toString();
                if (TextUtils.isEmpty(addressName)) {
                    ToastUtils.showShort(R.string.et_address_tips);
                    return;
                }
                if (TextUtils.isEmpty(selPath)) {
                    ToastUtils.showShort(R.string.cover_tips);
                    return;
                }
                WeddingBean weddingBean = new WeddingBean(groomName, brideName, mDataBinding.tvWeddingDate.getText().toString(),
                        locationName, addressName, selPath);
                CardPreviewActivity.sWeddingBean = weddingBean;
                CardPreviewActivity.position = position;
                startActivity(CardPreviewActivity.class);
                break;
            case R.id.tvWeddingDate://婚宴日期
                mySelDateDialog.show();
                break;
            case R.id.tvWeddingHost://婚宴举办地
                if (KeyboardUtils.isSoftInputVisible(this)) {
                    KeyboardUtils.hideSoftInput(this);
                }
                if (pvOptions != null) {
                    pvOptions.show();
                }
                break;
            case R.id.tvUploadCover://上传封面
            case R.id.ivCoverImg:
                getPermission();
                break;
            case R.id.ivCoverDelete://删除封面
                selPath = "";
                mDataBinding.tvUploadCover.setVisibility(View.VISIBLE);
                mDataBinding.ivCoverImg.setVisibility(View.GONE);
                mDataBinding.ivCoverDelete.setVisibility(View.GONE);
                break;
            //选择日期弹框
            case R.id.tvDialogSelDateCancel://取消
                mySelDateDialog.dismiss();
                break;
            case R.id.tvDialogSelDateRight://确定
                mySelDateDialog.dismiss();
                int year = wheelView1.getCurrentItem() + 1980;
                int moon = wheelView2.getCurrentItem() + 1;
                int day = wheelView3.getCurrentItem() + 1;
                selDate = year + "-" + (moon < 10 ? "0" + moon : moon) + "-" + (day < 10 ? "0" + day : day + "") + " ";
                mySelTimeDialog.show();
                break;
            //选择时间弹框
            case R.id.tvDialogSelTimeCancel://取消
                mySelTimeDialog.dismiss();
                break;
            case R.id.tvDialogSelTimeRight://确定
                mySelTimeDialog.dismiss();
                int hour = wheelView4.getCurrentItem();
                int minute = wheelView5.getCurrentItem();
                selDate += (hour < 10 ? "0" + hour : hour) + ":" + (minute < 10 ? "0" + minute : minute);
                mDataBinding.tvWeddingDate.setText(selDate);
                break;
        }
    }

    @Override
    protected void initData() {
        levelsListDate = new CityLevelsListDate(mContext);
        jsonBeans = levelsListDate.initJsonData("citys_data.json");
        arrayLists = levelsListDate.initJsonData1("citys_data.json");
        arrayLists1 = levelsListDate.initJsonData2("citys_data.json");
        showHyPickerView();
    }

    private void getPermission() {
        StkPermissionHelper.permission(StkPermissionHelper.Permission.ACCESS_IMAGE_VIDEO)
                .reqPermissionDesc(getString(R.string.get_picture_permission))
                .callback(new StkPermissionHelper.ACallback() {
                    @Override
                    public void onGranted() {
                        getImage();
                    }
                }).request();
    }

    private void getImage() {
        PhotoSelectorBuilder.builder(this)
                .mode(PhotoConfig.Mode.PHOTO)
                .minCount(1)
                .maxCount(1)
                .listener(new OnSelectResultListener<List<SelectMediaEntity>>() {
                    @Override
                    public void onResult(List<SelectMediaEntity> data) {
                        ArrayList<String> pathList = new ArrayList<>();
                        for (SelectMediaEntity entity : data) {
                            pathList.add(entity.getTargetPath());
                        }
                        selPath = pathList.get(0);
                        Glide.with(mContext).load(selPath).into(mDataBinding.ivCoverImg);
                        mDataBinding.tvUploadCover.setVisibility(View.GONE);
                        mDataBinding.ivCoverImg.setVisibility(View.VISIBLE);
                        mDataBinding.ivCoverDelete.setVisibility(View.VISIBLE);
                    }
                });
    }

    //选择日期弹框
    private void selDateDialog() {
        mySelDateDialog = new Dialog(mContext, R.style.DialogStyle);
        View inflate = LayoutInflater.from(mContext).inflate(R.layout.dialog_sel_date, null);
        mySelDateDialog.setContentView(inflate);
        //获取当前Activity所在的窗体
        Window dialogWindow = mySelDateDialog.getWindow();
        //设置Dialog从窗体中心弹出
        dialogWindow.setGravity(Gravity.BOTTOM);
        //获得窗体的属性
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        DisplayMetrics dm = getResources().getDisplayMetrics();
        lp.width = (int) (dm.widthPixels * 1);
        // 将属性设置给窗体
        dialogWindow.setAttributes(lp);
        TextView dialogCancel = inflate.findViewById(R.id.tvDialogSelDateCancel);
        TextView dialogRight = inflate.findViewById(R.id.tvDialogSelDateRight);
        wheelView1 = inflate.findViewById(R.id.wheel_view1);
        wheelView2 = inflate.findViewById(R.id.wheel_view2);
        wheelView3 = inflate.findViewById(R.id.wheel_view3);
        dialogCancel.setOnClickListener(this);
        dialogRight.setOnClickListener(this);
        wheelView1.setDividerColor(Color.parseColor("#FFEBED"));
        wheelView1.setTextColorCenter(Color.parseColor("#191919"));
        wheelView1.setLineSpacingMultiplier(2.5f);
        wheelView1.setDividerType(WheelView.DividerType.WRAP);
        wheelView1.setCurrentItem(43);
        wheelView1.setItemsVisibleCount(5);
        wheelView1.setCyclic(true);
        wheelView1.setTextSize(16);
        wheelView2.setDividerColor(Color.parseColor("#FFEBED"));
        wheelView2.setTextColorCenter(Color.parseColor("#191919"));
        wheelView2.setLineSpacingMultiplier(2.5f);
        wheelView2.setDividerType(WheelView.DividerType.WRAP);
        wheelView2.setCurrentItem(0);
        wheelView2.setItemsVisibleCount(5);
        wheelView2.setCyclic(true);
        wheelView2.setTextSize(16);
        wheelView3.setDividerColor(Color.parseColor("#FFEBED"));
        wheelView3.setTextColorCenter(Color.parseColor("#191919"));
        wheelView3.setLineSpacingMultiplier(2.5f);
        wheelView3.setDividerType(WheelView.DividerType.WRAP);
        wheelView3.setCurrentItem(0);
        wheelView3.setItemsVisibleCount(5);
        wheelView3.setCyclic(true);
        wheelView3.setTextSize(16);
        //设置滚轮数据
        List<String> listYear = new ArrayList<>();//年 1980-2040
        for (int i = 0; i < 61; i++) {
            listYear.add(String.valueOf(1980 + i));
        }
        List<String> listMonth = new ArrayList<>();//月 12
        for (int i = 0; i < 12; i++) {
            listMonth.add(String.valueOf((i + 1) < 10 ? "0" + (i + 1) : i + 1));
        }
        WheelAdapter adapter1 = new ArrayWheelAdapter(listYear);
        wheelView1.setAdapter(adapter1);
        WheelAdapter adapter2 = new ArrayWheelAdapter(listMonth);
        wheelView2.setAdapter(adapter2);
        setDayDate(31);//日 默认显示1月 共31天

        //监听月份滚动选择
        wheelView2.setOnItemSelectedListener(new OnItemSelectedListener() {
            @Override
            public void onItemSelected(int index) {
                index = index + 1;
                if (index == 1 || index == 3 || index == 5 || index == 7 || index == 8 || index == 10 || index == 12) {
                    //大月31天
                    setDayDate(31);
                } else if (index == 2) {
                    //2月判断是闰(29)还是平(28)
                    if (TimeUtils.isLeapYear(TimeUtils.getNowString(format), format)) {
                        setDayDate(29);
                    } else {
                        setDayDate(28);
                    }
                } else {
                    //小月30天
                    setDayDate(30);
                }
            }
        });
        //滚动到对应日期
        String date = TimeUtils.getNowString(new SimpleDateFormat("yyyy-MM-dd"));
        String[] split = date.split("-");
        int year = Integer.parseInt(split[0]);//年
        int moon = Integer.parseInt(split[1]);//月
        int day = Integer.parseInt(split[2]);//日
        wheelView1.setCurrentItem(year - 1980);
        wheelView2.setCurrentItem(moon - 1);
        wheelView3.setCurrentItem(day - 1);
    }

    //选择时间弹框
    private void selTimeDialog() {
        mySelTimeDialog = new Dialog(mContext, R.style.DialogStyle);
        View inflate = LayoutInflater.from(mContext).inflate(R.layout.dialog_sel_time, null);
        mySelTimeDialog.setContentView(inflate);
        //获取当前Activity所在的窗体
        Window dialogWindow = mySelTimeDialog.getWindow();
        //设置Dialog从窗体中心弹出
        dialogWindow.setGravity(Gravity.BOTTOM);
        //获得窗体的属性
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        DisplayMetrics dm = getResources().getDisplayMetrics();
        lp.width = (int) (dm.widthPixels * 1);
        // 将属性设置给窗体
        dialogWindow.setAttributes(lp);
        TextView dialogCancel = inflate.findViewById(R.id.tvDialogSelTimeCancel);
        TextView dialogRight = inflate.findViewById(R.id.tvDialogSelTimeRight);
        wheelView4 = inflate.findViewById(R.id.wheel_view1);
        wheelView5 = inflate.findViewById(R.id.wheel_view2);
        dialogCancel.setOnClickListener(this);
        dialogRight.setOnClickListener(this);
        wheelView4.setDividerColor(Color.parseColor("#FFEBED"));
        wheelView4.setTextColorCenter(Color.parseColor("#191919"));
        wheelView4.setLineSpacingMultiplier(2.5f);
        wheelView4.setDividerType(WheelView.DividerType.WRAP);
        wheelView4.setCurrentItem(0);
        wheelView4.setItemsVisibleCount(5);
        wheelView4.setCyclic(true);
        wheelView4.setTextSize(16);
        wheelView5.setDividerColor(Color.parseColor("#FFEBED"));
        wheelView5.setTextColorCenter(Color.parseColor("#191919"));
        wheelView5.setLineSpacingMultiplier(2.5f);
        wheelView5.setDividerType(WheelView.DividerType.WRAP);
        wheelView5.setCurrentItem(0);
        wheelView5.setItemsVisibleCount(5);
        wheelView5.setCyclic(true);
        wheelView5.setTextSize(16);
        //设置滚轮数据
        List<String> listHour = new ArrayList<>();//时
        for (int i = 0; i < 24; i++) {
            listHour.add(String.valueOf(i));
        }
        List<String> listMinute = new ArrayList<>();//分
        for (int i = 0; i < 60; i++) {
            listMinute.add(String.valueOf(i));
        }
        WheelAdapter adapter1 = new ArrayWheelAdapter(listHour);
        wheelView4.setAdapter(adapter1);
        WheelAdapter adapter2 = new ArrayWheelAdapter(listMinute);
        wheelView5.setAdapter(adapter2);
    }

    //设置天
    private void setDayDate(int num) {
        List<String> listDay = new ArrayList<>();//日 默认显示1月31天
        for (int i = 0; i < num; i++) {
            listDay.add(String.valueOf((i + 1) < 10 ? "0" + (i + 1) : i + 1));
        }
        WheelAdapter adapter3 = new ArrayWheelAdapter(listDay);
        wheelView3.setAdapter(adapter3);
    }

    /**
     * 初始化城市选择器
     */
    private void showHyPickerView() {
        //条件选择器
        pvOptions = new OptionsPickerBuilder(mContext, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                try {
                    mDataBinding.tvWeddingHost.setText(jsonBeans.get(options1).getREGION_NAME() + "-" +
                            jsonBeans.get(options1).getCity().get(options2).getREGION_NAME() + "-" +
                            jsonBeans.get(options1).getCity().get(options2).getRes().get(options3).getREGION_NAME());
                } catch (Exception e) {
                    mDataBinding.tvWeddingHost.setText(jsonBeans.get(options1).getREGION_NAME() + "-" +
                            jsonBeans.get(options1).getCity().get(options2).getREGION_NAME());
                }
            }
        }).setTitleText(getString(R.string.sel_area))//标题
                .setSubCalSize(18)//确定和取消文字大小
                .setTitleSize(18)//标题文字大小
                .setTitleColor(Color.parseColor("#191919"))//标题文字颜色
                .setSubmitColor(Color.parseColor("#EF4165"))//确定按钮文字颜色
                .setCancelColor(Color.parseColor("#80191919"))//取消按钮文字颜色
                .setTitleBgColor(Color.WHITE)//标题背景颜色 Night mode
                .setContentTextSize(16)//滚轮文字大小
                .build();
        pvOptions.setPicker(jsonBeans, arrayLists, arrayLists1);
    }

}